<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<title>防抖函数</title>
		<style type="text/css">
			* {
				padding: 0;
				margin: 0;
			}

			body,
			html {
				height: 100%;
				overflow: hidden;
			}

			#scrollWrap {
				height: 100%;
				overflow-y: auto;
			}

			.output {
				background: #00BFFF;
				opacity: 0.5;
			}
		</style>
	</head>
	<body>
		<div id="scrollWrap">
			<div style="height: 3000px;"></div>
		</div>


		<script type="text/javascript">
			// throttle 完整版
			function throttle(fn, wait, options) {
				let timeout, remaining, context, args;
				let previous = 0;
				// timeout等于null,代表定时器已经完成
				// 如果没有传options默认为空
				if (!options) {
					options = {};
					// 虽然没有声明options, 相当于window.options={}
				}
				let later = function() {
					// previous = +new Date();
					previous = options.immediate == false ? 0 : new Date().getTime();
					// +new Date() 等同于:new Date().getTime()
					timeout = null;
					fn.call(context, args);
					if (!timeout) context = args = null;
					console.log("最后执行的");
				};


				let throttled = function() {
					context = this;
					args = arguments;
					let now = +new Date();
					if (!previous && options.immediate === false) {
						previous = now;
					}
					// 下次触发 func 剩余的时间
					remaining = wait - (now - previous);
					// 代表我这个定时器执行完了 那么就执行n秒后(比如：3~6秒)的事件操作
					// 如果没有剩余的时间了
					if (remaining <= 0 ){
							if (timeout) {
								clearTimeout(timeout);
								timeout = null;
							}
							previous = now;
							// 立即执行
							fn.apply(context, args);
							if (!timeout) context = args = null;
						} else if (!timeout && options.last !== false) {
							timeout = setTimeout(later, remaining);
						}
					};
					throttled.cancel = function() {
						clearTimeout(timeout);
						timeout = null;
						previous = 0;
					};
					return throttled;
				}
		</script>
		<script type="text/javascript">
			var scrollWrap = document.querySelector("#scrollWrap");

			function output(e) {
				console.log(e.target.scrollTop);
			}

			scrollWrap.addEventListener('scroll', throttle(output, 100,{ immediate: true, last:false}))
		</script>
	</body>
</html>
